//
//  UserPageManager.m
//  JiuKuGospel
//
//  Created by jiukuyinyue on 15-8-10.
//  Copyright (c) 2015年 JiuKuForApp. All rights reserved.
//

#import "UserPageManager.h"
#import "NSString+MD5.h"

#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonHMAC.h>

@implementation UserPageManager{
    NSTimer         *_timer;
    JKNSTimerHolder         *_timingCloseTimer;
}
@synthesize usercode = _usercode;

IMPLEMENTATION_SINGLETON(UserPageManager)

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.WIFIStr = @"NO";
        self.playLoveStr = @"NO";
        self.musicYinzhi = @"默认";
        self.isWIFIPlay = YES;
        self.qiandaoDic = [NSMutableDictionary dictionary];
        
        [self loadUserCode];//读取usercode
        [self loadSystemNumber];//系统通知数
        [self loadNoticeNumber];//通知数
        [self loadSys_not_read];//后台记录系统没读的数
        [self loadMsg_not_read];//后台记录通知没读的数



        [self loadReadingTime];//读取阅读时间
        _timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(doTimer) userInfo:nil repeats:YES];
    }
    return self;
}
- (void)doTimer {
    self.readingTime++;
    //获取系统当前的时间戳
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [date timeIntervalSince1970]*1000;
    [[NSUserDefaults standardUserDefaults] setDouble:a forKey:@"readingTimeKeep"];//存储日期
    if(self.getReadTimeBlock != nil) {
        self.getReadTimeBlock(self.readingTime);
    }
}
-(void)setReadingTime:(NSInteger)readingTime{
    _readingTime = readingTime;
    [[NSUserDefaults standardUserDefaults] setInteger:readingTime forKey:@"readingTime"];
}
- (void)loadReadingTime {
    //根据日期判断是否已经启动,弹出推送
    NSUserDefaults *defaulut = [NSUserDefaults standardUserDefaults];
    // 从沙盒中读取上一次存储的日期
    double timenum = [defaulut doubleForKey:@"readingTimeKeep"];
    NSTimeInterval interval = timenum / 1000.0;// iOS 生成的时间戳是10位
    NSDate *boxDate = [NSDate dateWithTimeIntervalSince1970:interval];
    //校验日期
    //判断日期 是今日已经记录过
    if ([boxDate isToday]) {
        self.readingTime = [defaulut integerForKey:@"readingTime"];
    }else{
        self.readingTime = 0;
    }
}
#pragma mark -  定时关闭 setup  -
///创建定时关闭
- (void)setupTimingCloseingTime
{
    if (_timingCloseTimer == nil) {
        JKNSTimerHolder *timingCloseTimer = [[JKNSTimerHolder alloc] init];
        _timingCloseTimer = timingCloseTimer;
        
    }
    [_timingCloseTimer jk_startNSTimerWithTimeInterval:1
                                           repeatCount:self.timingCloseingTimeNum
                                         actionHandler:self
                                                action:@selector(doTimerTimingCloseing)];
}
- (void)doTimerTimingCloseing {
    self.timingCloseingTimeNum--;
    if(self.timingCloseingTimeBlock != nil) {
        self.timingCloseingTimeBlock(self.timingCloseingTimeNum);
    }
    if (self.timingCloseingTimeNum < 0) {
        if (_UserM.selectedRow != 0) {
            [_LCPlayer pause];
        }
        _UserM.selectedRow = 0;
        [self clearTimer];
    }
}
- (void)clearTimer {
    if(_timingCloseTimer != nil) {
        [_timingCloseTimer jk_cancelNSTimer];
    }
    _timingCloseTimer = nil;
    self.timingCloseingTimeNum = 0;
}
#pragma mark -  定时关闭 end  -
-(void)setUsercode:(NSString *)usercode{
    _usercode = usercode;
    [[NSUserDefaults standardUserDefaults] setObject:usercode forKey:@"usercode"];
}
///读取usercode
-(void)loadUserCode{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"usercode"] == nil) {
        self.usercode = @"";
    } else {
        self.usercode = [[NSUserDefaults standardUserDefaults] objectForKey:@"usercode"];
    }
}
-(void)setSystemNumber:(NSString *)systemNumber
{
    _systemNumber = systemNumber;
    [[NSUserDefaults standardUserDefaults] setObject:systemNumber forKey:@"systemNumber"];
}
-(void)loadSystemNumber
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"systemNumber"] == nil) {
        _systemNumber =  @"";
    } else {
        _systemNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"systemNumber"];
    }
}
-(void)setNoticeNumber:(NSString *)noticeNumber
{
    _noticeNumber = noticeNumber;
    [[NSUserDefaults standardUserDefaults] setObject:noticeNumber forKey:@"noticeNumber"];
}
-(void)loadNoticeNumber
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"noticeNumber"] == nil) {
        _noticeNumber = @"";
    } else {
        _noticeNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"noticeNumber"];
    }
}
#pragma mark - 后台记录的系统没读的数
-(void)setSys_not_read:(NSString *)sys_not_read
{
    _sys_not_read = sys_not_read;
    [[NSUserDefaults standardUserDefaults] setObject:sys_not_read forKey:@"sys_not_read"];
}
-(void)loadSys_not_read
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"sys_not_read"] == nil) {
        _sys_not_read = @"";
    } else {
        _sys_not_read = [[NSUserDefaults standardUserDefaults] objectForKey:@"sys_not_read"];
    }
}
#pragma mark - 后台记录的通知没读的数
-(void)setMsg_not_read:(NSString *)msg_not_read
{
    _msg_not_read = msg_not_read;
    [[NSUserDefaults standardUserDefaults] setObject:msg_not_read forKey:@"msg_not_read"];
}
-(void)loadMsg_not_read
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"msg_not_read"] == nil) {
        _msg_not_read = @"";
    } else {
        _msg_not_read = [[NSUserDefaults standardUserDefaults] objectForKey:@"msg_not_read"];
    }
}
-(void)setUserName:(NSString *)userName{
    [[NSUserDefaults standardUserDefaults] setObject:userName forKey:@"userName"];
}
-(NSString *)userName{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"userName"] == nil) {
        return @"";
    } else {
        return [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    }
}
-(void)setMobileNum:(NSString *)mobileNum{
    [[NSUserDefaults standardUserDefaults] setObject:mobileNum forKey:@"mobileNum"];
}
-(NSString *)mobileNum{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"mobileNum"];
}
-(void)setCredit:(NSString *)credit{
    [[NSUserDefaults standardUserDefaults] setObject:credit forKey:@"credit"];
}
-(NSString *)credit{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"credit"];
}
- (void)saveUserMessages
{
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    [userDefaults setObject:self.userID forKey:@"userID"];
    [userDefaults setObject:self.userImageUrl forKey:@"userImageUrl"];
    [userDefaults setObject:self.userName forKey:@"userName"];
    [userDefaults setObject:self.usercode forKey:@"usercode"];
    [userDefaults setObject:self.mbcode_md5 forKey:@"mbcode_md5"];
    [userDefaults setObject:self.groupid forKey:@"groupid"];
    [userDefaults setObject:self.salt forKey:@"salt"];
    [userDefaults setObject:self.play_notenjoy forKey:@"play_notenjoy"];
    [userDefaults setObject:self.play_qlty forKey:@"play_qlty"];
    [userDefaults setObject:self.signin forKey:@"signin"];

    [userDefaults setObject:self.qiandao forKey:@"qiandao"];
    [userDefaults setObject:self.qiandaoDic forKey:@"qiandaoDic"];
    [userDefaults setObject:self.WIFIStr forKey:@"WIFI"];
    [userDefaults setObject:self.playLoveStr forKey:@"playLoveStr"];
    [userDefaults setObject:self.musicYinzhi forKey:@"musicYinzhi"];

    [userDefaults synchronize];

}

- (void)getUserMessages
{
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    
    self.userID = [userDefaults objectForKey:@"userID"];
    self.userImageUrl = [userDefaults objectForKey:@"userImageUrl"];
    self.userName = [userDefaults objectForKey:@"userName"];
    self.mbcode_md5 = [userDefaults objectForKey:@"mbcode_md5"];
    self.groupid = [userDefaults objectForKey:@"groupid"];
    self.salt = [userDefaults objectForKey:@"salt"];
    self.play_notenjoy = [userDefaults objectForKey:@"play_notenjoy"];
    self.play_qlty = [userDefaults objectForKey:@"play_qlty"];
    self.signin = [userDefaults objectForKey:@"signin"];
    self.qiandao = [userDefaults objectForKey:@"qiandao"];
    if ([userDefaults objectForKey:@"qiandaoDic"]) {
        [self.qiandaoDic addEntriesFromDictionary:[userDefaults objectForKey:@"qiandaoDic"]];
    }
    NSString * str = [userDefaults objectForKey:@"WIFI"];
    if (str.length == 0) {
        self.WIFIStr = @"NO";
    }else{
        self.WIFIStr = str;
    }
    self.playLoveStr = [userDefaults objectForKey:@"playLoveStr"];
    self.musicYinzhi = [userDefaults objectForKey:@"musicYinzhi"];
    self.usercode = [userDefaults objectForKey:@"usercode"];


    if ( self.usercode.length !=0) {
        self.isLogin = YES;
    }else{
        self.usercode = @"";
    }
}
//退出的歌曲沙盒存储路径
- (NSString *)filePath:(NSString *)path
{
    NSString * documents = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    NSString * filePath = [documents stringByAppendingPathComponent:path];
    return filePath;
}
- (void)clearUserMessages
{
    self.userID = nil;
    self.userImageUrl = nil;
    self.userName = nil;
    NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:nil forKey:@"userID"];
    [userDefaults setObject:nil forKey:@"userImageUrl"];
    [userDefaults setObject:nil forKey:@"userName"];
    [userDefaults setObject:nil forKey:@"mbcode_md5"];
    [userDefaults setObject:nil forKey:@"groupid"];
    [userDefaults setObject:nil forKey:@"salt"];
    [userDefaults setObject:nil forKey:@"play_notenjoy"];
    [userDefaults setObject:nil forKey:@"play_qlty"];
    [userDefaults setObject:nil forKey:@"qiandao"];
    [userDefaults setObject:nil forKey:@"usercode"];
    [userDefaults setObject:nil forKey:@"signin"];

    [userDefaults synchronize];
}
#pragma mark - SHA256加密

- (void)hmacSHA256ShouQuanJiamiWithUserCode:(NSString *)userCode
{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];    //转为字符型
    
//        NSString *timeString = @"1505200306";
    NSString *appsecret = APPSECRET;
    //算法
    NSString * timekey = [self hmac:timeString withKey:appsecret];
    NSString * userkey = [self hmac:userCode withKey:timekey];
    NSString * accesskey = [self hmac:@"0" withKey:userkey];
    
    self.accesskey = accesskey;
    self.times = timeString;
}
- (NSString *)hmac:(NSString *)data withKey:(NSString *)key {
    const char *keyData = key.UTF8String;
    const char *strData = data.UTF8String;
    uint8_t buffer[CC_SHA256_DIGEST_LENGTH];
    
    CCHmac(kCCHmacAlgSHA256, keyData, strlen(keyData), strData, strlen(strData), buffer);
    return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH];
}
#pragma mark - 助手方法
/**
 *  返回二进制 Bytes 流的字符串表示形式
 *
 *  @param bytes  二进制 Bytes 数组
 *  @param length 数组长度
 *
 *  @return 字符串表示形式
 */
- (NSString *)stringFromBytes:(uint8_t *)bytes length:(int)length {
    NSMutableString *strM = [NSMutableString string];
    
    for (int i = 0; i < length; i++) {
        [strM appendFormat:@"%02x", bytes[i]];
    }
    
    return [strM copy];
}
- (NSString*)dictionaryToJson:(NSDictionary *)dic{
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
#pragma mark - 九酷福音  发现更多  商城
+ (NSString *)getUrlStrMove {
    NSString *key = @"#lskdflkas(*(jfkl214lkl,.,.mj";
    
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a * 1000];
    
    NSString * uid  = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
//     NSString * uid  = @"100";
    NSString *sign = [[NSString stringWithFormat:@"userid=%@&time=%@%@",uid,timeString,key] md5];
    
    return [NSString stringWithFormat:@"userid=%@&time=%@&sign=%@",uid,timeString,sign];
}
#pragma mark - 不带code的加密
- (void)NewhmacSHA256ShouQuanJiamiWithUserCode:(NSString *)userCode
{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];    //转为字符型

    //        NSString *timeString = @"1505200306";
    NSString *appsecret = APPSECRET;
    //算法
    NSString * timekey = [self hmac:timeString withKey:appsecret];
    NSString * userkey = [self hmac:@"" withKey:timekey];
    NSString * accesskey = [self hmac:@"0" withKey:userkey];
    self.Newaccesskey = accesskey;
    self.Newtimes = timeString;
}
@end
